package com.train.chatspring.controller;

import com.train.chatspring.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileUploadController {

    @Autowired
    private FileService fileService;

    @Value("${spring.web.resources.static-locations}")
    private String staticLocations;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("userId") String userId,
                             @RequestParam("friendName") String friendName) {
        try {
            // 调用 FileService 的 uploadFile 方法保存文件
            String filePath = fileService.uploadFile(file);
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file: " + e.getMessage();
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String filename) {
        try {
            // 调用 FileService 的 downloadFile 方法获取文件内容
            byte[] fileContent = fileService.downloadFile(filename);

            // 确定文件的媒体类型
            String contentType = getContentType(filename);

            // 返回文件流
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                    .body(fileContent);
        } catch (IOException e) {
            // 捕获文件读取异常并返回错误信息
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(("File not found or unreadable: " + filename).getBytes());
        }
    }

    @GetMapping(value = "/images/{filename}")
    public ResponseEntity<Resource> serveImage(@PathVariable String filename) throws MalformedURLException {
        // 从配置中获取静态资源路径
        String[] locations = staticLocations.split(",");
        for (String location : locations) {
            location = location.trim();
            if (location.startsWith("classpath:")) {
                location = location.substring("classpath:".length());
            } else if (location.startsWith("file:")) {
                location = location.substring("file:".length());
            }

            // 构建文件的完整路径
            Path filePath = Paths.get(location, filename).normalize();

            // 将文件路径包装为 Resource 对象
            Resource resource = new UrlResource(filePath.toUri());

            // 检查文件是否存在且可读
            if (resource.exists() && resource.isReadable()) {
                // 确定文件的媒体类型
                String contentType = getContentType(filename);
                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .body(resource); // 返回图片资源
            }
        }

        throw new RuntimeException("File not found or unreadable: " + filename);
    }

    private String getContentType(String filename) {
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            default:
                return "application/octet-stream";
        }
    }
}